package com.youlu.campus.service.commission;

import com.youlu.campus.entity.UserInviteRecord;
import com.youlu.campus.entity.commission.DistributorApply;
import com.youlu.campus.entity.commission.DistributorApplyStatusEnum;
import com.youlu.campus.entity.commission.DistributorCommission;
import com.youlu.campus.entity.commission.SharingCommissionDetail;
import com.youlu.campus.entity.commission.dto.CalCommissionDTO;
import com.youlu.campus.entity.commission.dto.DistributorAccountGradeDTO;
import com.youlu.campus.entity.commission.dto.SharingCommissionOrderDTO;
import com.youlu.campus.entity.commission.enums.SharingCommissionProfitStatus;
import com.youlu.campus.entity.dto.sms.SmsBaseInfoDTO;
import com.youlu.campus.entity.enums.SharingProfitOrderTypeEnum;
import com.youlu.campus.service.invite.UserInviteRecordService;
import com.youlu.campus.service.sms.SmsServerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;

/**
 * 佣金计算抽象类
 */
@Slf4j
public abstract class AbstractCommissionService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserInviteRecordService userInviteRecordService;

    @Autowired
    private DistributorGradeService distributorGradeService;

    @Autowired
    private DistributorApplyService distributorApplyService;

    @Autowired
    private SmsServerService smsServerService;


    /**
     * 分佣比例不能为0
     */
    public final static Double ZERO = 0d;

    /**
     * 获取当前佣金
     * @param activityId
     * @return
     */
    protected abstract Double getCurrentSharingCommissionRatio(String activityId,Integer businessType);

    /**
     * 下单用户是否来自邀请并且是否是分销者
     * @param invitedToUserId
     * @param activityId
     * @return
     */
    public  UserInviteRecord inviterDistributor(String invitedToUserId,String activityId){
        UserInviteRecord invitedToUser = userInviteRecordService.invitedSuccessByInvitedToUserIdAndActivityId(invitedToUserId, activityId);
        if (Objects.isNull(invitedToUser) ||!invitedToUser.getInviterDistributor()) {
           return null;
        }
        return invitedToUser;
    }

    public DistributorApply findByDistributorId(String distributorId){
        return distributorApplyService.findByUserId(distributorId, DistributorApplyStatusEnum.PASS.getValue());
    }


  public Integer doSharingCommissionAmount(SharingCommissionOrderDTO sharingCommissionOrderDto){
      String activityId = sharingCommissionOrderDto.getActivityId();
      String category = sharingCommissionOrderDto.getCategory();
      String orderNo = sharingCommissionOrderDto.getOrderNo();
      Integer totalFee = sharingCommissionOrderDto.getTotalFee();
      String transactionId = sharingCommissionOrderDto.getTransactionId();
      Date payTime = sharingCommissionOrderDto.getPayTime();
      Double currentSharingCommissionRatio = this.getCurrentSharingCommissionRatio(activityId,
              sharingCommissionOrderDto.getBusinessType());
      if (currentSharingCommissionRatio.compareTo(ZERO) == 0) {
          log.error("【订单分拥】订单分账比例 不能为0 或者超过60% AbstractCommissionService.doSharingCommissionAmount  order->{}| " +
                  "category->{}| " +
                  "分账比例 ", orderNo, category, currentSharingCommissionRatio);
          return ZERO.intValue();
      }
      try {
          DistributorCommission distributorCommission = sharingCommissionOrderDto.getDistributorCommission();
          BigDecimal totalAmount = new BigDecimal(totalFee);
          CalCommissionDTO calCommissionDto = distributorGradeService.doCalCommission(distributorCommission.getUserId(), currentSharingCommissionRatio, totalFee);
          int sharingProfitAmount = totalAmount.multiply(calCommissionDto.getCurrentCommissionRatio()).intValue();
          log.info("【订单分拥】AbstractCommissionService.doSharingCommissionAmount  order->{}| category->{}| ratio->{}|" +
                          " sharingProfitAmount ->{}",
                  orderNo, category, currentSharingCommissionRatio, sharingProfitAmount);
          if (sharingProfitAmount <= 0) {
              log.error("【订单分拥】AbstractCommissionService.doSharingCommissionAmount 分拥金额错误不能为0 order->{}| category->{}| " +
                              "ratio->{}|" +
                              " sharingProfitAmount ->{}",
                      orderNo, category, currentSharingCommissionRatio, sharingProfitAmount);
          }
          Query query = new Query();
          query.addCriteria(Criteria.where("orderNo").is(orderNo));
          boolean exists = this.mongoTemplate.exists(query, SharingCommissionDetail.class);
          if (exists) {
              log.warn("【订单分拥】订单已存在 orderNo:{}",orderNo);
              return ZERO.intValue();
          }
          if(StringUtils.isNotBlank(distributorCommission.getMobile())){
              try {
                  String smsAmount = BigDecimal.valueOf(sharingProfitAmount).divide(BigDecimal.valueOf(100), 2,
                          BigDecimal.ROUND_HALF_UP).toString();
                  SmsBaseInfoDTO dto = SmsBaseInfoDTO.builder()
                          .phone(distributorCommission.getMobile())
                          .signName("梦想跳动")
                          .templateId("1699318")
                          .smsType(SmsBaseInfoDTO.SmsType.SMS_TEM)
                          .templateParamSet(new String[]{distributorCommission.getName(),smsAmount})
                          .build();
                 smsServerService.sendSmsMsg(dto);
              }catch (Exception e){
                  log.error("分拥短信 发送错误 mobile:{}",distributorCommission.getMobile(),e);
              }
          }

          Update update = new Update();
          update.set("activityId", activityId);
          //update.set("activityName", sharingCommissionOrderDto.getActivityName());
          update.set("sharingProfitOrderType", SharingProfitOrderTypeEnum.valueOf(category));
          update.set("baseSharingCommissionRatio", currentSharingCommissionRatio);
          update.set("incSharingCommissionRatio", calCommissionDto.getIncCommissionRatio());
          update.set("sharingCommissionRatio", calCommissionDto.getCurrentCommissionRatio().multiply(new BigDecimal(100)).doubleValue());
          update.set("orderAmount", totalFee);
          update.set("sharingCommissionAmount", sharingProfitAmount);
          update.set("sharingCommissionStatus", SharingCommissionProfitStatus.UNSETTLED.getValue());
          update.set("appId", sharingCommissionOrderDto.getAppId());
          update.set("merchantId", sharingCommissionOrderDto.getMerchantId());
          update.set("merchantName", sharingCommissionOrderDto.getMerchantName());
          update.set("refund",Boolean.FALSE);
          update.set("distributorCommission",distributorCommission);
          Date now = new Date();
          update.setOnInsert("createdTime", now);
          update.set("updatedTime", now);
          update.set("transactionId", transactionId);
          update.set("payTime", payTime);
          FindAndModifyOptions findAndModifyOptions = new FindAndModifyOptions();
          findAndModifyOptions.returnNew(Boolean.TRUE);
          findAndModifyOptions.upsert(Boolean.TRUE);
          this.mongoTemplate.findAndModify(query, update, findAndModifyOptions, SharingCommissionDetail.class);
          return sharingProfitAmount;
      }catch (Exception e){
          log.error("【订单分拥】AbstractCommissionService.doSharingCommissionAmount  order->{}| category->{}| ratio->{} " +
                          "error",
                  orderNo, category, currentSharingCommissionRatio,e);
          return ZERO.intValue();
      }

      //sharingCommissionInfo.getDigitalCaSharingProfitRatio()
  }
}
